/**
 * @file: shell.js
 * @brief: 简化版WebSocket Shell客户端，只保留基本读写功能
 * @date: 2025-12-06
 *
 **************************/

/**
 * Shell客户端类 - 简化版，只保留基本的WebSocket连接和消息收发功能
 */
class ShellClient {
    /**
     * 构造函数
     * @param {string} serverUrl - Shell服务器URL
     * @param {function} onMessage - 消息接收回调函数
     */
    constructor(serverUrl, onMessage) {
        // 默认连接到localhost:9090
        this.serverUrl = serverUrl || 'localhost:9090';
        this.socket = null;
        this.isConnected = false;
        
        // 回调函数
        this.onMessage = onMessage || function() {};
    }

    /**
     * 连接Shell服务器
     */
    connect() {
        try {
            // 检查浏览器是否支持WebSocket
            if (typeof WebSocket === 'undefined') {
                console.error('WebSocket is not supported in this browser');
                return;
            }
            
            // 解析服务器地址并添加WebSocket协议前缀
            let wsUrl = this.serverUrl;
            if (!wsUrl.startsWith('ws://') && !wsUrl.startsWith('wss://')) {
                const parts = wsUrl.split(':');
                const host = parts[0];
                const port = parseInt(parts[1]) || 9090;
                wsUrl = `ws://${host}:${port}`;
            }
            
            console.log(`Connecting to shell server at ${wsUrl}...`);
            
            // 创建WebSocket连接
            this.socket = new WebSocket(wsUrl);
            
            // WebSocket事件处理
            this.socket.onopen = () => {
                console.log('Shell WebSocket connection established');
                this.isConnected = true;
            };
            
            // 处理接收到的消息
            this.socket.onmessage = (event) => {
                try {
                    const data = event.data;
                    this.onMessage(data);
                } catch (error) {
                    console.error('Failed to process shell message:', error);
                }
            };
            
            // 处理连接错误
            this.socket.onerror = (error) => {
                console.error('Shell WebSocket error:', error);
                this.isConnected = false;
            };
            
            // 处理连接关闭
            this.socket.onclose = (event) => {
                console.log('Shell WebSocket connection closed:', event.code, event.reason);
                this.isConnected = false;
            };
        } catch (error) {
            console.error('Failed to initialize shell connection:', error);
        }
    }

    /**
     * 发送命令到Shell服务器
     * @param {string} command - 要执行的命令
     * @returns {boolean} - 是否发送成功
     */
    sendCommand(command) {
        if (!this.isConnected || !this.socket || this.socket.readyState !== WebSocket.OPEN) {
            console.error('Cannot send command: WebSocket is not connected');
            return false;
        }
        
        try {
            // 确保命令以\r\n结束
            let commandWithEol = command;
            if (!commandWithEol.endsWith('\r\n')) {
                if (commandWithEol.endsWith('\n')) {
                    commandWithEol = commandWithEol.slice(0, -1) + '\r\n';
                } else if (commandWithEol.endsWith('\r')) {
                    commandWithEol += '\n';
                } else {
                    commandWithEol += '\r\n';
                }
            }
            this.socket.send(commandWithEol);
            return true;
        } catch (error) {
            console.error('Failed to send command:', error);
            return false;
        }
    }

    /**
     * 断开与Shell服务器的连接
     */
    disconnect() {
        if (this.socket) {
            console.log('Closing shell WebSocket connection...');
            this.socket.close();
            this.socket = null;
            this.isConnected = false;
        }
    }
}

/**
 * 导出模块（兼容浏览器环境）
 */
if (typeof window !== 'undefined') {
    window.ShellClient = ShellClient;
}